import { Component, OnInit } from '@angular/core';
import {Users} from '../../model/Users';
import {AuthService} from '../../services/auth.service';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
import {SetheadComponent} from '../sethead/sethead.component';
import {ToastService} from '../../services/toast.service';
import {SetpassComponent} from '../setpass/setpass.component';

@Component({
  selector: 'app-userinfo',
  templateUrl: './userinfo.component.html',
  styleUrls: ['./userinfo.component.css']
})
export class UserinfoComponent implements OnInit {
  u:Users;
  constructor(private authservice:AuthService
  ,private modalService: NgbModal
  ,private toastservice:ToastService) {
    this.u=new Users();
  }

  ngOnInit(): void {
    this.loadMyUserInfo();
  }

  loadMyUserInfo(){
    this.authservice.getMyUserInfo()
      .then((data:any)=>{
        if (data.msg=='ok'){
          this.u=new Users();
          this.u=data.obj;
        }
      })
  }

  openSetHead(){
    const refModel=this.modalService.open(SetheadComponent);
    refModel.result
      .then((result:any)=>{
        console.log(result);
        this.setUserHead(result);
      })

  }

  setUserHead(path:string){
    this.authservice.setUserHead(path)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.loadMyUserInfo();
        }
        else {
          this.toastservice.showError('修改头像错误，请刷新后重试');
        }
      })
  }

openSetPass(){
  const refModel=this.modalService.open(SetpassComponent);
  refModel.result
    .then((result:any)=>{
      console.dir(result);
      if(result.oldpass!=null&&result.newpass!=null){
        this.changePass(result.oldpass,result.newpass);
      }


    })
}

changePass(oldpass:string,newpass:string){
    this.authservice.setpass(oldpass,newpass)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.toastservice.showinfo('密码重设成功');
        }
        else if(data.msg=='oldpasserror'){
          this.toastservice.showWarning('原密码错误');
        }
        else{
          this.toastservice.showError('修改错误，请刷新后重试');
        }
      })
}



}
